import React, { useState, useEffect, useImperativeHandle } from 'react';
import City from './components/cityTree';
import { Button } from 'antd';
import CityJson from '@/common/city';
console.log(React);
const cityTree = React.forwardRef((props, ref) => {
  const { city = [] } = props.detail;

  const [data, setData] = useState([]);
  const [visible, setVisible] = useState(false);
  const initCityData = (data) => {
    let newList = [];
    let list = data.reduce((item, val) => {
      return [...item, ...val.cityCode];
    }, []);
    CityJson.forEach((item) => {
      const { children } = item;
      children.forEach((item) => {
        const { value } = item;
        if (list.includes(value)) {
          newList.push(item);
        }
      });
    });
    return newList;
  };
  useEffect(() => {
    setData(initCityData(city));
  }, []);
  useImperativeHandle(ref, () => ({
    getData: filterData('code'),
  }));
  const filterData = (type = 'str') => {
    let CityObj = {};
    let cityListObj = {};
    CityJson.forEach((item) => {
      const { value } = item;
      CityObj[value] = item.label;
    });
    data.forEach((item) => {
      const { pid, level } = item;
      if (!cityListObj[pid] && level != 1) {
        cityListObj[pid] = [];
      }
      level != 1 && cityListObj[pid].push({ ...item });
    });
    let str = '';
    let dataList = [];
    Object.values(cityListObj).forEach((item) => {
      let oneObj = {};
      item.forEach((val, index) => {
        if (index == 0) {
          oneObj.provinceCode = val['pid'];
          oneObj.cityCode = [];
          str += CityObj[val['pid']] + '(';
        } else if (index === item.length - 1) {
          str += val.label + ') ,';
        } else {
          str += val.label + '、';
        }
        oneObj.cityCode.push(val.value);
      });
      dataList.push(oneObj);
    });

    if (type === 'str') {
      return str;
    } else {
      return dataList;
    }
  };

  return (
    <div style={{ padding: '0px 68px 18px' }}>
      区域选择: {filterData('str')}
      <Button onClick={() => setVisible(true)} type={'link'}>
        请选择城市
      </Button>
      <City
        data={filterData('code').length ? filterData('code') : city}
        onChange={(e) => {
          setData(e);
          setVisible(false);
        }}
        onClose={() => setVisible(false)}
        show={visible}
      ></City>
    </div>
  );
});
export default cityTree;
